from __future__ import print_function

import configparser
import os

from twisted.internet.ssl import optionsForClientTLS
from twisted.internet import protocol, defer, endpoints, task
from twisted.mail import imap4
from twisted.python import failure

user_pswd_cfg = os.environ['user_pswd']
cf = configparser.ConfigParser()
cf.read(user_pswd_cfg, encoding='utf-8')
username = cf.get('qq_email', 'qq_email_user')
password = cf.get('qq_email', 'qq_email_pswd')
strport = "tls:qq.com:993"


class IMAP4Demo:
    @defer.inlineCallbacks
    def main(self, reactor):
        endpoint = endpoints.clientFromString(reactor, strport)
        factory = protocol.Factory.forProtocol(imap4.IMAP4Client)
        try:
            client = yield endpoint.connect(factory)
            yield client.login(username, password)
            yield client.select('INBOX')
            info = yield client.fetchEnvelope(imap4.MessageSet(1))
            print('First message subject:', info[1]['ENVELOPE'][1])
        except:
            print("IMAP4 client interaction failed")
            failure.Failure().printTraceback()


def _test_imap4():
    """
    _test_imap4()
    # TODO 发送失败
    """
    id = IMAP4Demo()
    task.react(id.main)


if __name__ == '__main__':
    _test_imap4()
